import { ControlType as TYPE } from "@components";
import { Button, Space, Spin,message } from "antd";
import { useMainContext } from '@contexts/MainContext'
import { findWeatherTypeGrade, findUnitArea } from "@apis/indexApi";
import { useState, useRef } from "react";
import { RULE_REQUIRED, RULE_ARRAY } from "@rules";

const useFieldsORColumns = ( edit ) => {
    const { isButtomShow } = useMainContext()
    const queryFormRef = useRef("queryFormRef");
    const modalFormRef = useRef("modalFormRef");
    const [WeatherTypes, setWeatherTypes] = useState([])
    const [unitAreas, setUnitAreas] = useState([])
    const [labelLoading, setLabelLoading] = useState(false)

    const findWeatherType = async (formRef) => {
        setWeatherTypes([])
        const weatherType = formRef.current?.getFieldValue('weatherType')
        if (!weatherType) return message.error('请先选择天气类型')

        setLabelLoading(true)
        const newWeatherTypes = await findWeatherTypeGrade({weatherType})
        setLabelLoading(false)
        setWeatherTypes(newWeatherTypes)
    }

    const getUnitArea = async (formRef, row, setModalLoading) => {
        setUnitAreas([])
        const unitCode = formRef.current?.getFieldValue('unitCode')
        if (!unitCode) return message.error('请先选择影响机构')

        setLabelLoading(true)
        const newUnitAreas = await findUnitArea(unitCode)
        setLabelLoading(false)
        setUnitAreas(newUnitAreas)

        if (!row) return
        const { cfgAreaIdList } = row
        const newValue = cfgAreaIdList?.length === newUnitAreas?.length ? ['all'] : cfgAreaIdList
        modalFormRef.current?.setFieldValue('untrueCfgAreaIdList', newValue)
        setModalLoading(false)
    }

    const selectConfig = (name, label, codeKey) => {
        return {
          name,
          label,
          codeKey,
          controlType: TYPE.SELECT,
          allowClear: true,
          showSearch: true,
          optionFilterProp: "children",
          filterOption: (input, option) => option.children.toLowerCase()?.includes(input.toLowerCase()),
          notFoundContent: labelLoading ? <Spin size="small" /> : null,
        }
      }

    const columns = [
        { title: '影响机构',dataIndex: 'unitName',key: 'unitName', ellipsis: true, open: true, width: 160 },
        { title: '区域名称', dataIndex: 'areaNameListStr', key: 'areaNameListStr', ellipsis: true, open: true, width: 160 },
        { title: '天气类型', dataIndex: 'weatherTypeName', key: 'weatherTypeName', open: true, width: 100 },
        { title: '天气类型等级', dataIndex: 'weatherTypeGradeName', key: 'weatherTypeGradeName', open: true, width: 100 },
        { 
            title: '异常天气时间', dataIndex: 'abnormalWeatherTime', key: 'abnormalWeatherTime', open: true, width: 200,
            render: (text, record) => {
                return <span>{record.abnormalWeatherTimeStart} ~ {record.abnormalWeatherTimeEnd}</span>
            }
        },
        { title: '数据更新时间', dataIndex: 'updateTime', key: 'updateTime', open: true, width: 160, },
        { title: '状态', dataIndex: 'statusName', key: 'statusName', open: true, width: 100 },
        // { title: '数据来源', dataIndex: 'dataSource', key: 'dataSource', open: true },
        {
            title: "操作",
            dataIndex: 'operationCol',
            key: 'operationCol',
            open: true,
            width: 100,
            fixed: 'right',
            render: (_, record) => {
                return (
                    <Space>
                        {isButtomShow('020102') && <Button type="primary" onClick={() => edit(record)}>编辑</Button>}
                    </Space>
                )
            }
        }
    ]

    const fields = [
        { 
          ...selectConfig('weatherType','天气类型','WeatherType'),
          onSelect: (value, option) => {
            if (!option?.value) return
            queryFormRef.current?.setFieldValue('weatherTypeGrade', null)
          },
          onClear: () => {
            queryFormRef.current?.setFieldValue('weatherTypeGrade', null)
          }
        },
        { 
          options: WeatherTypes,
          ...selectConfig('weatherTypeGrade','天气类型等级'),
          onFocus: () => findWeatherType(queryFormRef)
        },
        { ...selectConfig('unitCode','影响机构','userAuthUnits') },
        { name: 'areaName', label: '区域名称', controlType: TYPE.INPUT }, 
        { name: 'abnormalWeatherTime', label: '异常天气时间', controlType: TYPE.DATE_RANGE_PICKER, linkageFields: ['abnormalWeatherTimeStart', 'abnormalWeatherTimeEnd'], showTime:{ format: 'HH' } }, 
        { name: 'updateTime', label: '数据更新时间', controlType: TYPE.DATE_RANGE_PICKER, linkageFields: ['updateTimeStart', 'updateTimeEnd'], showTime: true }, 
        { ...selectConfig("status","状态","status") },
    ]

    const modalFields = [
        { 
            ...selectConfig('weatherType','天气类型','WeatherType'),
            rules: [RULE_REQUIRED],
            onSelect: (value, option) => {
              if (!option?.value) return
              modalFormRef.current?.setFieldValue('weatherTypeGrade', null)
              setWeatherTypes([])
            },
          },
          { 
            options: WeatherTypes,
            ...selectConfig('weatherTypeGrade','天气类型等级'),
            rules: [RULE_REQUIRED],
            onFocus: () => findWeatherType(modalFormRef)
          },
        {
            ...selectConfig('unitCode','影响机构','userAuthUnits'),
            rules: [RULE_REQUIRED],
            onSelect: (value, option) => {
              if (!option?.value) return
              modalFormRef.current?.setFieldValue('cfgAreaIdList', undefined)
            },
            onClear: () => {
              modalFormRef.current?.setFieldValue('cfgAreaIdList', undefined)
            }
        }, 
        {
            options: unitAreas,
            ...selectConfig('untrueCfgAreaIdList','区域名称'),
            rules: [RULE_REQUIRED],
            controlType: TYPE.SELECTALL,
            onChange: (value, option=[]) => {
              modalFormRef.current?.setFieldValue('cfgAreaIdList', option.map(item => item.value))
            },
            onFocus: () => getUnitArea(modalFormRef),
            optionTemplate: option => <>{option.label}</>
        },
        { 
          options: [],
          ...selectConfig('cfgAreaIdList','区域名称'),
          selectmode: "multiple",
          mode: 'hidden'
      }, 
        { name: 'abnormalWeatherTime', label: '异常天气时间', controlType: TYPE.DATE_RANGE_PICKER, linkageFields: ['abnormalWeatherTimeStart', 'abnormalWeatherTimeEnd'], showTime:{ format: 'HH' }, rules: [RULE_ARRAY] },  
        { ...selectConfig("status","状态","status"), rules: [RULE_REQUIRED] },
    
    ]

    return {
        queryFormRef,
        fields,
        columns,
        modalFormRef,
        modalFields,
        findWeatherType, getUnitArea
    }
}

export default useFieldsORColumns